'use strict';

const TODOLIST = require('../../class/TodoList');
var moment = require('moment');
module.exports = {
  post: {
    ':_id/:_owner': {
      method: (req, res, next) => {
        TODOLIST.detail(req.params._id).then(todo => {
          todo.origin = todo._id;
          delete todo._id;

          new TODOLIST(todo, req.user, req.params._owner).then(ntodo => {
            res.json(ntodo);
          }).catch(next);
        }).catch(next);
      }
    },
    '': {
      method: (req, res, next) => {
        let user = req.user;

        let body = req.body;

        new TODOLIST(body, user).save().then(todo => {
          res.json(todo);
          console.log('set new schedule:', todo._id.toString(), todo.create_at);
          schedule.setSchedule(todo._id.toString(), moment(todo.create_at).add(5, 'hours'));
        }).catch(next);
      }
    }
  },
  get: {
    'count': {
      method: (req, res, next) => {
        TODOLIST.count(req.user._id, req.query).then(count => {
          res.json(count);
        }).catch(next);
      }
    },
    'detail/:_id': {
      method: (req, res, next) => {
        let _id = req.params._id;

        TODOLIST.detail(_id).then(todo => {
          if (!todo) return res.send('');
          todo.createAt = new Date(todo.createAt).Format('YYYY-MM-DD');
          todo.completeAt && (todo.completeAt = new Date(todo.completeAt).Format('YYYY-MM-DD'));
          let len = todo.children.length;
          if (!len || todo.status == 1) todo.process = 100;
          else {
            let finished = Array.prototype.filter.call(todo.children, child => {
              return child.status == 1;
            }).length;
            todo.process = parseInt(finished / len * 100);
          }
          res.json(todo);
        }).catch(next);
      }
    },
    'list': {
      method: (req, res, next) => {
        TODOLIST.list(req.user._id, req.query).then(list => {
          res.json(list);
        }).catch(next);
      }
    }
  },
  put: {
    'success/:_id': {
      method: (req, res, next) => {
        let _id = req.params._id;
        TODOLIST.success(_id).then(todo => {
          res.json(todo);
        }).catch(next);
      }
    },
    ':_id': {
      method: (req, res, next) => {
        let _id = req.params._id;

        let data = req.body;

        TODOLIST.update(_id, data).then(todo => {
          res.json(todo);
        }).catch(next);
      }
    }
  },
  delete: {
    ':_id': {
      method: (req, res, next) => {
        TODOLIST.del(req.params._id).then(result => {
          res.json(result || {});
        }).catch(next);
      }
    }
  }
};
